package com.panopset.nls;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Vector;
import static com.panopset.Util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * National Language System (NLS) flag icons.
 *
 *
 * @author Karl Dinwiddie
 *
 */
public class AvailableLanguages {
    public final Vector<String> langIds;

    /**
     * AvailableLanguages constructor
     *
     * @param directory
     *            Directory where translations live, en.properties, etc.
     */
    public AvailableLanguages(String directory) {
        langIds = new Vector<String>();
        File dir = new File(directory);
        if (!dir.isDirectory()) {
            throw new RuntimeException("Must specify a directory: " + directory);
        }
        for (File f : dir.listFiles()) {
            if (f.isFile()) {
                String fn = f.getName();
                int i = fn.lastIndexOf(PERIOD);
                if (i == 2) {
                    langIds.add(fn.substring(0, i));
                }
            }
        }
    }

    /**
     * Save NLS language names properties files to a directory.
     *
     * @param directoryPath
     */
    public void saveLangNamesToDirectory(String directoryPath) {
        for (String langId : langIds) {
            String from = "/com/panopset/nls/babel/" + langId + "/names.txt";
            String to = directoryPath + "/" + langId + "_names.txt";
            try {
                com.panopset.Util.copyLibraryResource(from, to);
            } catch (IOException ex) {
                log("from: " + from);
                log("to: " + to);
                Logger.getLogger(AvailableLanguages.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Save all images to a directory
     *
     * @param targetPath
     *            path to directory, either full or relative to runtime.
     * @throws IOException
     */
    public void saveResourcesToDirectory(String targetPath) throws IOException {
        FlagIcons.asFlagIcons().spritePackage.saveResourcesToDirectory(targetPath, langIds);
    }

    private String flagIconsString;

    @Override
    public String toString() {
        if (flagIconsString == null) {
            StringWriter sw = new StringWriter();
            for (String s : langIds) {
                sw.append(s);
                sw.append(getReturnChar());
            }
            flagIconsString = sw.toString();
        }
        return flagIconsString;
    }

}
